import { _decorator, Component, UIOpacity, UITransform } from 'cc';
import { GChapter, GEnemy, IActor, IEnemy, StateTypeEnum } from '../Common';
import DataManager from '../Runtime/DataManager';
const { ccclass, property } = _decorator;

@ccclass('HPBar')
export class HPBar extends Component {


    @property(UITransform)
    barBg: UITransform

    @property(UITransform)
    bar: UITransform

    @property(UIOpacity)
    nodeOpacity: UIOpacity

    entity: IActor | IEnemy
    entityHeight: number
    setSize(w: number, h: number) {
        const UITr = this.node.getComponent(UITransform)
        UITr.width = w
        this.entityHeight = h
    }

    update() {
        let hpMax: number
        if ((this.entity as IActor).attr) {
            hpMax = (this.entity as IActor).attr.hpMax
        } else {
            hpMax = GEnemy[this.entity.type].hp * GChapter[DataManager.Ins.state.levelState.chapter][DataManager.Ins.state.levelState.level]?.hpRatio || 0
        }
        // 满血隐藏
        if (this.entity.hp / hpMax >= 1) {
            this.nodeOpacity.opacity = 0
        } else {
            this.nodeOpacity.opacity = 255
        }
        this.bar.width = this.entity.hp / hpMax * this.barBg.width
        const { x, y } = this.entity.position
        this.node.setPosition(x, y + this.entityHeight / 2)
        if (this.entity.state == StateTypeEnum.dead) {
            this.node.destroy()
        }
    }

}